<?php
	session_start();

	//Conexión a la bd
	$link = mysqli_connect('localhost', 'root', '') or die("Failed to connect to MySQL: " . mysql_error());
	if (mysqli_connect_errno()) {
	        echo 'Failed to connect to MySQL';
	        exit;
	}
	$sql = "USE web_db";
	$query = mysqli_query($link,$sql);

	$name = $_POST['name'];
	$desc = $_POST['desc'];
	$country = $_POST['country'];
	$date = date('Y-m-d');
	$num_pilots = $_POST['num_pilots'];

	//Coger el siguiente número para el id de la misión
	$sql = "SELECT MAX(miss_nr)
			FROM mission";
	$query = mysqli_query($link,$sql);
	$aux = mysqli_fetch_row($query);
	$miss_nr = $aux[0] + 1;

	//Inserción de datos, por defecto la misión no está completa
	$sql = "INSERT INTO mission (miss_nr, date, name, description, status) VALUES ('$miss_nr', '$date', '$name', '$desc', 'Not-Complete')";
	$data = mysqli_query($link,$sql);
    if($data){
    	echo "Mission registered";
    	echo "<br>";
    }

    //Inserción en la tabla de country_mission
    echo "Insertando ".$country." para la mision ".$miss_nr."<br>";
    $sql = "INSERT INTO country_mission (code, mission_nr) VALUES ('$country', '$miss_nr')";
	$data = mysqli_query($link,$sql);
    if($data){
    	echo "Mission in country registered";
    	echo "<br>";
    }

	//Y ya insertar en la tabla mecha mission cada participante
	echo "Hay " . $num_pilots . " pilotos<br>";
	while($num_pilots > 0){
		$num_pilots = $num_pilots - 1;
		$mec = 'mec_id' . $num_pilots;
		$mec_id = $_POST[$mec];
		$sql = "INSERT INTO mech_mission (mec_id, mission_nr) VALUES ('$mec_id', '$miss_nr')";
		$data = mysqli_query($link,$sql);
	    if($data){
	    	echo "Pilot asigned to mission";
	    	echo "<br>";
	    }
	}

	//Reiniciar la lista de pilotos disponibles
	$_SESSION['pilots_list'] = array();

    header("location:missions.php");
?>